from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for, abort, Response
from Config import db
from models.my_model import Post, User, R, UserRo, Comment, Like
from flask_login import current_user, login_required

page_like = Blueprint("like", __name__)


@page_like.route("/post/like", methods=['POST', 'GET'])
@login_required
def post_like():
    data = request.get_json()
    data = like_plus(2, current_user.id, data["postId"])
    return data


@page_like.route("/comment/like", methods=['POST', 'GET'])
@login_required
def comment_like():
    data = request.get_json()
    data = like_plus(3, current_user.id, data["commentId"])
    return data


@page_like.route("/user/like", methods=['POST', 'GET'])
@login_required
def user_like():
    data = request.get_json()
    data = like_plus(1, current_user.id, data["userId"])
    return data

def like_plus(like_type, user_id, target):
    print("?")
    old_like = Like()
    post = Post()
    like_type = like_type
    user_id = user_id
    target = target
    new_like: Like = Like(
        user_id=current_user.id,
    )
    if like_type == 1:
        old_like: Like = Like.query.filter(Like.user_id == user_id,
                                           Like.target_user_id == target).first()
        new_like.target_user_id = target
    elif like_type == 2:
        post: Post = Post.query.filter(Post.id == target).first()
        old_like: Like = Like.query.filter(Like.user_id == user_id,
                                           Like.target_post_id == target).first()
        new_like.target_post_id = target
    elif like_type == 3:
        old_like: Like = Like.query.filter(Like.user_id == user_id,
                                           Like.target_comment_id == target).first()
        new_like.target_comment_id = target
    session: db.session = db.session()
    if old_like:
        session.delete(old_like)
        if like_type == 2:
            post.like_count -= 1
            session.merge(post)
        data = 0
    else:
        if like_type == 2:
            post.like_count += 1
            session.merge(post)
        session.add(new_like)
        data = 1
    session.commit()
    session.close()
    return jsonify({'code': "200", "msg": "insert_OK", "data": data})
    # return jsonify(
    #     R(200, "insert_OK",nihao =1)
    #     .define()
    # )
